package com.akk.config.shiro;

import com.akk.common.enums.AdminEnums;
import com.akk.module.admin.entity.Admin;
import com.akk.module.admin.service.AdminMenuService;
import com.akk.module.admin.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * 认证
 */
@Component
public class AdminRealm extends AuthorizingRealm {
    @Autowired
    private AdminService adminService;
    @Autowired
    private AdminMenuService menuService;
    
    /**
     * 授权(验证权限时调用)
     */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Admin admin = (Admin) principals.getPrimaryPrincipal();
		//用户权限列表
		Set<String> permsSet = menuService.getAdminPermissions(admin);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(permsSet);
		return info;
	}

	/**
	 * 认证(登录时调用)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String account = (String) token.getPrincipal();
		String password = new String((char[]) token.getCredentials());
		List<Admin> admins = adminService.findByAccount(account);
        //密码错误
        if(!password.equals(admins.get(0).getPassword())) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }
        //账号锁定
        if(admins.get(0).getAdminStatus() == AdminEnums.StatusEnum.DISABLED.getValue()){
        	throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admins.get(0), password, getName());
        return info;
	}

}
